<template>
  <div class="body">
    <van-nav-bar fixed>
      <template #left>
        <van-icon name="arrow-left" @click="$router.back()" />
      </template>
      <template #right>
        <van-icon name="ellipsis" />
      </template>
    </van-nav-bar>
    <div>
      <van-loading class="loadinfo" color="#0094ff" vertical v-if="load"
        >加载中</van-loading
      >
      <div class="del" v-else-if="err" @click="getDetails">
        加载失败，点击重新加载
      </div>
      <div class="main" v-else-if="success">
        <Like :obj="obj"></Like>
        <div v-html="obj.content" class="matter" ref="content"></div>
        <div class="evaluate">
          <van-button
            icon="good-job-o"
            :type="obj.attitude === 1 ? 'danger' : 'default'"
            round
            @click="likeArticle(obj.art_id)"
            >点赞</van-button
          >
          <van-button
            icon="delete-o"
            :type="obj.attitude === 0 ? 'danger' : 'default'"
            round
            class="dislike"
            @click="targetLiking(obj.art_id)"
            >不喜欢</van-button
          >
        </div>
        <van-empty description="还没有人评论哦" v-if="objLoad.length === 0">
        </van-empty>
        <div v-else>
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            @load="onLoad"
            :immediate-check="false"
          >
            <div class="load" v-for="obj in objLoad" :key="obj.com_id">
              <van-image
                class="loadPhoto"
                v-if="obj.aut_photo"
                round
                width="1.5rem"
                height="1.5rem"
                fit="cover"
                :src="obj.aut_photo"
              />
              <div class="loadInfo">
                <div class="loadUser">
                  <span>{{ obj.aut_name }}</span>
                  <div>
                    <van-icon
                      name="good-job-o"
                      @click="targetLike(obj.com_id, obj.is_liking)"
                      :color="obj.is_liking ? 'red' : ''"
                    />{{ obj.is_liking ? obj.like_count : "赞" }}
                  </div>
                </div>
                <div class="test">
                  {{ obj.content }}
                </div>
                <div class="bnm">
                  <span>{{ obj.pubdate | time }}</span>
                  <van-button
                    class="reply"
                    round
                    size="mini"
                    @click="huiFu(obj.aut_name, obj.com_id, obj)"
                    >{{ obj.reply_count }}回复</van-button
                  >
                </div>
              </div>
            </div>
          </van-list>
        </div>
      </div>
      <div class="del" v-else>文章已被删除</div>
      <van-tabbar fixed>
        <van-button round size="normal" class="b" @click="iput"
          >写评论</van-button
        >
        <div>
          <van-badge :content="total_count">
            <div class="toutiao iconpinglun news" />
          </van-badge>
        </div>
        <div>
          <van-icon
            v-if="obj.is_collected"
            name="star"
            color="#f00"
            size="25"
            @click="hoarding(false)"
          />
          <van-icon v-else name="star-o" size="25" @click="hoarding(true)" />
        </div>
        <div
          class="toutiao iconfenxiang switch"
          @click="showShare = true"
        ></div>
      </van-tabbar>
      <van-popup
        v-model="show"
        class="popup"
        position="bottom"
        :style="{ height: '30%' }"
        ><van-field
          v-model.trim="test"
          rows="5"
          autosize
          type="textarea"
          maxlength="50"
          :placeholder="flag ? `@${this.username}` : '请输入留言'"
          show-word-limit
          @keyup.enter.stop="addTest()"
          ref="a"
        >
          <template #extra>
            <van-button
              size="small"
              @click="addTest"
              :disabled="test.length === 0"
              >发送</van-button
            >
          </template>
        </van-field>
      </van-popup>
      <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
      />
    </div>
    <van-popup
      v-model="show1"
      position="bottom"
      closeable
      close-icon-position="top-left"
      @close="flag = false"
      :style="{ height: '100%' }"
    >
      <div class="vanPopup">
        <LoadItem :itemLoad="itemLoad" @targetLike="targetLike"></LoadItem>
      </div>
      <div>全部评论</div>
      <div class="vanPopup1">
        <LoadItem
          v-for="item in loadItems"
          :key="item.com_id"
          :itemLoad="item"
          @targetLike="targetLike"
        ></LoadItem>
      </div>
      <van-button round size="normal" class="huiFuButton" @click="iput"
        >@{{ itemLoad.aut_name }}</van-button
      >
    </van-popup>
  </div>
</template>

<script>
import Like from '@/components/like.vue'
import LoadItem from '@/components/loadItem.vue'
import {
  details,
  delHoard,
  hoard,
  addLikeArticle,
  delLikeArticle,
  delLike,
  addLike
} from '@/api/article.js'
import { getLoading, addLoading, like, delLiking } from '@/api/loading.js'
import { ImagePreview } from 'vant'
export default {
  name: 'articleItem',
  components: { Like, LoadItem },
  props: {
    article_id: {
      type: [Number, String], // 如果是从路径过来的就是字符串，如果是从点击文章进来的就是数字
      require: true
    }
  },
  data () {
    return {
      load: true,
      err: false,
      success: false,
      obj: {},
      test: '',
      objLoad: [],
      itemLoad: {},
      flag: false,
      show: false,
      show1: false,
      username: '',
      userId: '',
      showShare: false,
      images: [],
      loading: false,
      error: false,
      finished: false,
      offset: 0,
      endId: 0,
      loadItems: [],
      total_count: 0,
      options: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '朋友圈', icon: 'wechat-moments' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' }
        ],
        [
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
          { name: '小程序码', icon: 'weapp-qrcode' }
        ]
      ]
    }
  },
  methods: {
    iput () {
      this.show = true
      setTimeout(() => {
        this.$refs.a.focus()
      }, 0)
    },
    onSelect () {
      this.showShare = false
    },
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const {
          data: { data }
        } = await getLoading({
          type: 'a',
          source: this.obj.art_id.toString(),
          offset: this.offset,
          limit: 5
        })
        if (this.objLoad.length > 1) {
          // 去重，防止后台返回一样的数据都渲染到页面
          for (let i = 0; i < data.results.length; i++) {
            var flag = true
            for (let j = 0; j < this.objLoad.length; j++) {
              if (this.objLoad[j].com_id === data.results[i].com_id) {
                flag = false
                break
              }
            }
            if (flag) this.objLoad.push(data.results[i])
          }
        }
      } catch (error) {
        this.error = true
      }
      // 加载状态结束
      this.loading = false
      if (this.total_count === this.objLoad.length) {
        this.finished = true
      }
    },
    // 对文章点赞
    async likeArticle (target) {
      if (this.obj.attitude === 1) {
        const { status } = await delLikeArticle(target)
        if (status === 204) {
          this.obj.attitude = -1
          this.$toast('取消点赞成功')
        }
      } else {
        const { status } = await addLikeArticle({ target })
        if (status === 201) {
          this.obj.attitude = 1
          this.$toast('点赞成功')
        }
      }
    },
    // 对文章不喜欢
    async targetLiking (target) {
      if (this.obj.attitude === 0) {
        const { status } = await addLike(target)
        if (status === 204) this.obj.attitude = -1
      } else {
        const { status } = await delLike({ target })
        if (status === 201) this.obj.attitude = 0
      }
    },
    // 收藏操作
    async hoarding (flag) {
      if (flag) {
        const { status } = await hoard(this.obj.art_id)
        if (status === 201) {
          this.$toast('收藏成功')
          this.obj.is_collected = true
        } else {
          this.$toast('操作失败')
        }
      } else {
        const { status } = await delHoard(this.obj.art_id)
        if (status === 204) {
          this.$toast('取消收藏')
          this.obj.is_collected = false
        } else {
          this.$toast('操作失败')
        }
      }
    },
    // 写评论操作
    async addTest () {
      if (this.test === '') return (this.show = false)
      if (this.flag) {
        const {
          data: {
            data
          }
        } = await addLoading({
          target: this.userId,
          content: this.test,
          art_id: this.obj.art_id
        })
        this.loadItems.unshift(data.new_obj)
        await this.getLoad('a')
      } else {
        const {
          data: {
            data
          }
        } = await addLoading({
          target: this.obj.art_id,
          content: this.test
        })
        this.objLoad.unshift(data.new_obj)
        this.total_count++
      }
      this.show = false
      this.test = ''
    },
    // 对评论点赞
    async targetLike (target, flag) {
      if (flag) {
        this.delLoad(target)
        this.getLoad('a')
      } else {
        const { status } = await this.addLoad(target)
        if (status === 201) {
          this.getLoad('a')
          this.$toast('点赞成功')
        }
      }
    },
    // 对获取文章进行封装
    async getDetails () {
      try {
        const {
          data: { data }
        } = await details(this.article_id)
        this.obj = data
        // 要想获取数据里面的img标签，必须在获取到数据后，这里不能在mounted钩子函数里面获取，因为请求是异步的
        setTimeout(() => {
          this.$refs.content.querySelectorAll('img').forEach((img, index) => {
            this.images.push(img.src)
            img.onclick = () => {
              ImagePreview({
                images: this.images,
                startPosition: index
              })
            }
          })
        }, 0)
        this.load = false
        this.err = false
        this.success = true
      } catch (error) {
        this.err = true
      }
    },
    // 对获取评论进行封装
    async getLoad (type) {
      const {
        data: { data }
      } = await getLoading({
        type,
        source: this.obj.art_id.toString(),
        limit: 5
      })
      this.offset = data.last_id
      this.objLoad = data.results
      this.total_count = data.total_count
    },
    // 对点赞评论进行封装
    async addLoad (target) {
      return await like({ target })
    },
    // 对取消评论进行封装
    async delLoad (target) {
      await delLiking(target)
      this.$toast('取消成功')
    },
    // 回复评论
    async huiFu (name, id, obj) {
      this.show1 = true
      this.itemLoad = obj
      this.flag = true
      this.username = name
      this.userId = id
      const {
        data: { data }
      } = await getLoading({ type: 'c', source: id })
      this.loadItems = data.results
    }
  },
  async created () {
    // 获取文章
    await this.getDetails()
    // 获取评论
    await this.getLoad('a')
  }
}
</script>

<style lang="less" scoped>
.main,
.loadinfo,
.del {
  margin: 97px 0;
}
.loadinfo {
  display: flex;
  align-items: center;
}
.del {
  text-align: center;
}
/deep/.van-nav-bar {
  height: 97px;
  background-color: rgb(236, 236, 236);
}
.spanTab {
  font-size: 28px;
}
/deep/ .matter {
  width: 100vw;
  white-space: pre-wrap;
  overflow: hidden;
  font-size: 28px;
  padding: 0 25px;
  box-sizing: border-box;
  h3,
  p {
    margin: 0;
  }
  p {
    img {
      width: 100%;
    }
  }
  pre {
    background-color: #cfcfcf;
    margin: 0;
    padding: 30px;
    overflow: auto;
  }
}
/deep/.van-tabbar {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  width: 100vw;
  font-size: 34px;
  input[type="text"] {
    width: 368px;
    height: 62px;
    border-radius: 62px;
    border: 1px solid #ccc;
    padding-left: 30px;
  }
  input[type="checkbox"] {
    position: relative;
  }
}
.news,
.switch {
  font-size: 45px;
}
/deep/van-button {
  font-size: 25px;
}
.evaluate {
  display: flex;
  justify-content: center;
  margin: 30px 0;
  .dislike {
    width: 198px;
    margin-left: 30px;
  }
}
.load {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
/deep/.van-image img {
  width: 100%;
  height: 100%;
}
.loadInfo {
  padding-top: 25px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-bottom: 20px;
  width: 570px;
  color: #000;
  font-size: 38px;
  .loadUser {
    display: flex;
    justify-content: space-between;
    padding-bottom: 20px;
    span {
      font-size: 42px;
      color: #666699;
    }
  }

  .test {
    font-size: 50px;
  }
  .bnm {
    padding-top: 20px;
    font-size: 30px;
    display: flex;
    align-items: center;
    .reply {
      margin-left: 20px;
      width: 134px;
    }
  }
}
.b {
  padding: 0 90px;
}
.popup {
  display: flex;
  align-items: center;
  .van-cell {
    align-items: center;
  }
}
.huiFuButton {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}
.vanPopup {
  margin-top: 90px;
}
.vanPopup1 {
  padding-top: 40px;
  height: 770px;
  overflow-y: auto;
}
</style>
